/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

//
//  AppDelegate.m
//  bsl-sdk
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//  Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//

#import "AppDelegate.h"
#import "NavigationViewController.h"
#import "SplashViewController.h"
#import "ZillaAccessData.h"

#import "CApplication.h"


/* 需要知道的事：
 1，证书需要打入至少两台的本地测试机  ，要开发者证书
 2，updateDeviceTokenForPushNotificationByAsychronous 的token 的传入是否正确
 3,  updateDeviceTokenForPushNotificationByAsychronous  与登陆是否需要分先后顺序
*/

@implementation AppDelegate

- (id)init{
    /** If you need to do any extra app-specific initialization, you can do it here
     *  -jm
     **/
    NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    int cacheSizeMemory = 8 * 1024 * 1024; // 8MB
    int cacheSizeDisk = 32 * 1024 * 1024; // 32MB

    NSURLCache* sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];

    [NSURLCache setSharedURLCache:sharedCache];

    self = [super init];
    return self;
}

+(AppDelegate*)appDelegate{
    return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}

#pragma mark UIApplicationDelegate implementation

/**
 * This is main kick off after the app inits, the views and Settings are setup here. (preferred - iOS4 and up)
 */
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{
    [application setApplicationIconBadgeNumber:0];
    // 本地通知设置

    //改写user-agent
    @autoreleasepool {
        
        UIWebView* webView=[[UIWebView alloc] init];
        NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
        
        
        
        
        NSString *newUagent = [NSString stringWithFormat:@"%@ ChameleonAPP",secretAgent];
        NSDictionary *dictionary = [[NSDictionary alloc]
                                    initWithObjectsAndKeys:newUagent, @"UserAgent",nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
        
    }
    

    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }  else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }

    CGRect screenBounds = [[UIScreen mainScreen] bounds];

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        
        [application setStatusBarStyle:UIStatusBarStyleLightContent];
        [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    }
    
    self.window = [[UIWindow alloc] initWithFrame:screenBounds];
    
    self.window.autoresizesSubviews = YES;
    
    
    ZillaAccessData* activeSession=[ZillaAccessData activeSession];
    
    NSBundle* bundle = [NSBundle mainBundle];
    activeSession.appKey = [bundle objectForInfoDictionaryKey:@"C_AppKey"];
    
    activeSession.appSecret=[bundle objectForInfoDictionaryKey:@"C_AppSecret"];
    
    activeSession.urlSchemeSuffix=[bundle objectForInfoDictionaryKey:@"C_UrlSchemeSuffix"];
    
    CApplication* cApplication=[CApplication sharedApplication];
    [cApplication initModulesConfig:application didFinishLaunchingWithOptions:launchOptions];
    
    self.navController=[[CubeNavigationViewController alloc] initWithRootViewController:[[CubeSplashViewController alloc] init]];
    [self.navController setNavigationBarHidden:YES];
    self.window.rootViewController = self.navController;

    
    [self.window makeKeyAndVisible];
    
    return YES;
}

//HNA
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken{


    NSLog(@"application token did success");
    if ([_deviceToken length]<1)
        return;
    
    NSString* token = [[[[_deviceToken description]
                         stringByReplacingOccurrencesOfString:@"<" withString:@""]
                        stringByReplacingOccurrencesOfString:@">" withString:@""]
                       stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:CDVRemoteNotification object:token];

    
    [[CApplication sharedApplication] application:application didRegisterForRemoteNotificationsWithDeviceToken:_deviceToken];
}

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"application token did failed:%@\n",error);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:CDVRemoteNotificationError object:error];

    [[CApplication sharedApplication] application:application didFailToRegisterForRemoteNotificationsWithError:error];
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{

    [application cancelAllLocalNotifications];
    [[CApplication sharedApplication] application:application didReceiveRemoteNotification:userInfo];
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // IOS 7 Support Required
    completionHandler(UIBackgroundFetchResultNewData);
    
    [application cancelAllLocalNotifications];
    [[CApplication sharedApplication] application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];

}



- (void)applicationDidBecomeActive:(UIApplication *)application{
    [application setApplicationIconBadgeNumber:0];
    [[CApplication sharedApplication] applicationDidBecomeActive:application];
}

- (void)applicationWillResignActive:(UIApplication *)application{
    [[CApplication sharedApplication] applicationWillResignActive:application];
}

- (void)applicationDidEnterBackground:(UIApplication *)application{
    [[CApplication sharedApplication] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application{
    [[CApplication sharedApplication] applicationWillEnterForeground:application];
}

// repost the localnotification using the default NSNotificationCenter so multiple plugins may respond
- (void) application:(UIApplication*)application
    didReceiveLocalNotification:(UILocalNotification*)notification{
    [application setApplicationIconBadgeNumber:0];
    [[NSNotificationCenter defaultCenter] postNotificationName:CDVLocalNotification object:notification];
    
    [[CApplication sharedApplication] application:application didReceiveLocalNotification:notification];

}

- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [[CApplication sharedApplication] applicationDidReceiveMemoryWarning:application];
}


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [[CApplication sharedApplication] application:application handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation{
    
    if (!url) {
        return NO;
    }
    
    // all plugins will get the notification, and their handlers will be called
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];
    

    
    return [[CApplication sharedApplication] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
    
    if (!url) {
        return NO;
    }
    
    // all plugins will get the notification, and their handlers will be called
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];

    
    return [[CApplication sharedApplication] application:application openURL:url options:options];
}

- (void)applicationWillTerminate:(UIApplication *)application{
    [[CApplication sharedApplication] applicationWillTerminate:application];
}
- (void)applicationSignificantTimeChange:(UIApplication *)application{
    [[CApplication sharedApplication] applicationSignificantTimeChange:application];
}

- (void)application:(UIApplication *)application willChangeStatusBarOrientation:(UIInterfaceOrientation)newStatusBarOrientation duration:(NSTimeInterval)duration{
    [[CApplication sharedApplication] application:application willChangeStatusBarOrientation:newStatusBarOrientation duration:duration];
}

- (void)application:(UIApplication *)application didChangeStatusBarOrientation:(UIInterfaceOrientation)oldStatusBarOrientation{
    [[CApplication sharedApplication] application:application didChangeStatusBarOrientation:oldStatusBarOrientation];
}

- (void)application:(UIApplication *)application willChangeStatusBarFrame:(CGRect)newStatusBarFrame{
    [[CApplication sharedApplication] application:application willChangeStatusBarFrame:newStatusBarFrame];
}

- (void)application:(UIApplication *)application didChangeStatusBarFrame:(CGRect)oldStatusBarFrame{
    [[CApplication sharedApplication] application:application didChangeStatusBarFrame:oldStatusBarFrame];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    [[CApplication sharedApplication] application:application didRegisterUserNotificationSettings:notificationSettings];
}


- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler{
    [[CApplication sharedApplication] application:application handleActionWithIdentifier:identifier forLocalNotification:notification completionHandler:completionHandler];
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void(^)())completionHandler{
    [[CApplication sharedApplication] application:application handleActionWithIdentifier:identifier forRemoteNotification:userInfo withResponseInfo:responseInfo completionHandler:completionHandler];
    
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler{
    [[CApplication sharedApplication] application:application handleActionWithIdentifier:identifier forRemoteNotification:userInfo completionHandler:completionHandler];
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forLocalNotification:(UILocalNotification *)notification withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void(^)())completionHandler{
    
    [[CApplication sharedApplication] application:application handleActionWithIdentifier:identifier forLocalNotification:notification withResponseInfo:responseInfo completionHandler:completionHandler];

}

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler{
    
    [[CApplication sharedApplication] application:application performFetchWithCompletionHandler:completionHandler];
}

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void(^)(BOOL succeeded))completionHandler{
    
    [[CApplication sharedApplication] application:application performActionForShortcutItem:shortcutItem completionHandler:completionHandler];
}

- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{
    [[CApplication sharedApplication] application:application handleEventsForBackgroundURLSession:identifier completionHandler:completionHandler];
}

- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(nullable NSDictionary *)userInfo reply:(void(^)(NSDictionary * __nullable replyInfo))reply{
    [[CApplication sharedApplication] application:application handleWatchKitExtensionRequest:userInfo reply:reply];

}

- (void)applicationShouldRequestHealthAuthorization:(UIApplication *)application{
    [[CApplication sharedApplication] applicationShouldRequestHealthAuthorization:application];
}

- (void)applicationProtectedDataWillBecomeUnavailable:(UIApplication *)application{
    [[CApplication sharedApplication] applicationProtectedDataWillBecomeUnavailable:application];
}

- (void)applicationProtectedDataDidBecomeAvailable:(UIApplication *)application{
    [[CApplication sharedApplication] applicationProtectedDataWillBecomeUnavailable:application];
}







@end
